package com.bsoft.wx.config.shiro;


import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.bsoft.wx.execption.EmosExection;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author hdh
 * @ Data   :Created in 21:32 2023/1/31
 * @ Description jwt 工具类
 * @ Modified By: hdh
 * @ Version : 1.0
 */
@Component
@Slf4j
public class JwtUtil {
    //密钥18.
    @Value("${emos.jwt.secret}")
    private String secret;
    //过期时间（天）
    @Value("${emos.jwt.expire}")
    private int expire;

    //创建token
    public String createToken(int userId) {
        log.info("expire" + expire);
        Date date = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, expire);

        log.info("secret" + secret);
        //创建加密算法
        Algorithm algorithm = Algorithm.HMAC256(secret);
        //内部类
        JWTCreator.Builder builder = JWT.create();
        String token = builder.withClaim("userId", userId).withExpiresAt(date).sign(algorithm);
        return token;
    }

    //得到用户id
    public int getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asInt();
        } catch (Exception e) {
            throw new EmosExection("令牌无效");
        }
    }

    //验证token
    public void verifierToken(String token) {
        //创建加密算法对象40.
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm).build();
        verifier.verify(token);
    }

}
